package com.zyp.messageboard.controller.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter({"/*"})
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String requestURI = httpRequest.getRequestURI();

        // 允许未登录用户访问的资源列表
        boolean isPublicResource = requestURI.endsWith("/login.jsp")
                || requestURI.endsWith("/messageList")
                || requestURI.endsWith("/login")
                || requestURI.endsWith("/css/*")
                || requestURI.endsWith("/js/*")
                || requestURI.endsWith("/images/*");

        if (session == null || session.getAttribute("user") == null) {
            if (!isPublicResource) {
                httpResponse.sendRedirect("login.jsp");
                return;
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code, if needed
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }
}
